package com.shanghaionstar.utils;

import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.onstar.cn.api.OperateDAAPReportService;
import com.onstar.cn.api.OperateReportService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.EncryptUtil;

import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.sqlite.entities.RequestEventReportEntity;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.mag.enumtype.OSType;
import com.shanghaionstar.enumtype.OperateType;
import com.shanghaionstar.report.bean.DynamicDTO;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.report.model.ReportModel;
import com.shanghaionstar.report.pool.PoolThread;
import com.shanghaionstar.report.pool.PoolThreadExecutor;
import com.shanghaionstar.sqlite.OperaterReportDBService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author Xiaofeng Feng
 * @Title: OperateReportUtil.java
 * @Description:事件上传Report
 * @date 2015年8月19日 下午2:15:18
 */
public class OperateReportUtil {
    public Context context;
    public static final String CONTENT_SUCCESS = "success";
    public static final String CONTENT_FAIL = "fail";
    public static OperateReportUtil reportUtil;
    public static final String pattern = "yyyy-MM-dd HH:mm:ss";
    private static OperaterReportDBService reportDbService;
    private final static int limitCount = 1;
    private final static int MAX_LIMIT = 5000;
    private static final LogManager logger = LogManager.getInstance(); // 记录日志
    //    private static RequestEventReportEntity EventReport = new RequestEventReportEntity();
    private static Boolean isCountFull = false; // 本地记录是否满50条

    public OperateReportUtil(Context context) {
        this.context = context;
    }

    public static OperateReportUtil getInstance(Context context) {
        if (reportUtil == null)
            reportUtil = new OperateReportUtil(context);
        return reportUtil;
    }

//    public static void operateEventReport(String functionid, OperateType operateType, Context context,
//                                          boolean isLoginedSuccess) {
//        operateEventReport(functionid, operateType, context,
//                isLoginedSuccess, "content");
//    }

    /*
     * @Description: 统一处理发送到服务端的操作 及逻辑处理 isLoginedSuccess:标志位 true:登录后并且成功了
     * false:非登录后调用后登录后失败调用
     */
    public static void operateEventReport(String functionid, OperateType operateType, Context context,
                                          boolean isLoginedSuccess, String content) {
        RequestEventReportEntity EventReport = new RequestEventReportEntity();
//        alterTableReportForMro(context);
        LogManager.getInstance().d("report content:" + content);
        Integer count = 0;
        if (context == null)
            return;
        /////////////////////////////////////////////////////封装json报文//////////////////////////////////////////////////
        /*
         * {"id":0,"functionID":"F0001","timestamp":"2015-07-28 16:47:08","vin":"hhhhhhhh", "operation":"click","startTimestamp":"2015-07-28 16:47:08",
		 * "endTimestamp" :"2015-07-28 16:47:08","content":"content","role":"owner"}
		 */

        DeviceUtil util = new DeviceUtil(context);
        EventReport.setAppVersion(util.getAppVersion());
        String accountId = ApplicationUtil.getInstance().getAccountId();
        EventReport.setAccountID(accountId);
        EventReport.setOsType(OSType.ANDROID.value());
        EventReport.setDeviceType(Build.MODEL);
        EventReport.setDeviceId(new DeviceUtil(context).getDeviceID());

        String startTime = getDateFromPattern(pattern);
        EventReport.setFunctionID(functionid);// functionid
        //EventReport.setTimestamp(getTimeStamp());// 操作时间
        EventReport.setTimestamp(startTime);// 操作时间
        if (ApplicationUtil.getInstance().getCurrentVehicle()!=null) {
            EventReport.setVin(ApplicationUtil.getInstance().getCurrentVehicle().getVin()); // VIN
        } else {
            EventReport.setVin(""); // VIN
        }
        EventReport.setOperation(operateType.getStringValue());    // 操作
        EventReport.setStartTimestamp(startTime);                    // 开始时间
        EventReport.setEndTimestamp(startTime);                        // 结束时间
        EventReport.setContent(content);                            // 关键内容
        EventReport.setRole(ApplicationUtil.getInstance().getLoginRole()); // 角色
        String ipdID = ApplicationUtil.getInstance().getIdpID();
        if (!TextUtils.isEmpty(ipdID)) {
            EventReport.setIdpID(ipdID);
        }
        try {
            List<RequestEventReportEntity> listdata = new ArrayList<RequestEventReportEntity>();
            reportDbService = new OperaterReportDBService(context);
            listdata = reportDbService.getList(false);
            if (isLoginedSuccess) {                                // isLoginedSuccess:标志位 true:登录后并且成功了直接发送到服务端  false:非登录后调用后登录后失败调用
                 //遍历集合
                listdata.add(EventReport);
                EventReport.setData(listdata);
                isCountFull = true;
                EventReport.setDaapContent(new Gson().toJson(new ReportModel().getAdaptReport(listdata, context)));
                SenderDAAPReport(EventReport, context);
            } else {                                                // 本地记录满50条上传到Report
                long addId = reportDbService.insert(EventReport);    // 将记录保存到本地数据库中
                if (addId >= 1) {                                    // 添加成功后再查总条数
                    count = reportDbService.getCount();
                    if (count >= MAX_LIMIT) {
                        reportDbService.deleteAll(null, false);
                    } else if (count >= limitCount) {                        // 满50条上传
                        EventReport.setData(listdata);    //遍历集合
                        isCountFull = true;
                        EventReport.setDaapContent(new Gson().toJson(new ReportModel().getAdaptReport(listdata, context)));
                        SenderDAAPReport(EventReport, context);
                    }
                }
            }
        } catch (final Exception e) {
            LogManager.getInstance().d(e.getMessage());
//            reportDbService.deleteAll(null, false);
//            MyPost.post(new Runnable() {
//                @Override
//                public void run() {
//                    AlertDialogUtil.showAlertDialog(mContext, "", e.getMessage());
//                }
//            });
        }
    }

    public static void operateEventReportFroMro(final RequestEventReportEntity mEventReport, final Context context) {

        PoolThread poolThread = PoolThreadExecutor.getThreadPollExecutor().getExecutorService();
        if (!poolThread.isOn()) {
            poolThread.start();
        }
        poolThread.execute(new Runnable() {
            @Override
            public void run() {
                ReportModel reportModel = new ReportModel();
                DynamicDTO dynamicDTO = reportModel.getDynamicDTO(context, new ReportReqParam.ReportReqParamBuilder()
                        .channelId("0")
                        .deviceType("0")
                        .objectID("")
                        .objectType("9")
                        .operationType("")
                        .result("0")
                        .type("0").createReportReqParam());
                operateEventReportFroMroImp(mEventReport, context, GsonHelper.toJson(dynamicDTO));
            }
        });
    }

//    Success / Fail

    /*
     * @Description: 统一处理发送到服务端的操作 及逻辑处理 isLoginedSuccess:标志位 true:登录后并且成功了
     * false:非登录后调用后登录后失败调用
     */
    public static void operateEventReportFroMroImp(RequestEventReportEntity mEventReport, Context context, String content) {
//        alterTableReportForMro(context);
        RequestEventReportEntity EventReport = new RequestEventReportEntity();
        LogManager.getInstance().d("report content for mro:" + content);
        LogManager.getInstance().d("report mEventReport for mro:" + mEventReport.toString());
        Integer count = 0;
        /////////////////////////////////////////////////////封装json报文//////////////////////////////////////////////////

       /* "idpID": "ONSTARM50850147",
                "startTimestamp": "2016-09-05 17:18:36.554",
                "endTimestamp": "2016-09-05 17:18:36.554",
                "timestamp": "2016-09-05 17:18:36.554",
                "functionID": "F6032",
                "vin": "LSGKR5WL0G0011E33",
                "deviceId": "c48caf3b38d7d23a9733391ee84529b0a908b410",
                "operation": "CLICK",
                "deviceType": "iPhone OS 9.3.5",
                "osType": "IPHONE",
                "role": "OWNER",
                "accountID": "1201765008",
                "appVersion": "7.0.0",
                "content": ""
*/
        DeviceUtil util = new DeviceUtil(context);
        mEventReport.setAppVersion(util.getAppVersion());
        String accountId = ApplicationUtil.getInstance().getAccountId();
        mEventReport.setAccountID(accountId);
        mEventReport.setOsType(OSType.ANDROID.value());
        mEventReport.setContent(content);
        mEventReport.setDeviceType(Build.MODEL);
        mEventReport.setDeviceId(new DeviceUtil(context).getDeviceID());
        String startTime = getDateFromPattern(pattern);
        mEventReport.setTimestamp(startTime);// 操作时间
        if (ApplicationUtil.getInstance().getCurrentVehicle() !=null){
            mEventReport.setVin(ApplicationUtil.getInstance().getCurrentVehicle().getVin()); // VIN
        } else {
            mEventReport.setVin(""); // VIN
        }
        mEventReport.setRole(ApplicationUtil.getInstance().getLoginRole()); // 角色
        String ipdID = ApplicationUtil.getInstance().getIdpID();
        if (!TextUtils.isEmpty(ipdID)) {
            mEventReport.setIdpID(ipdID);
        }
        try {
            reportDbService = new OperaterReportDBService(context);
            long addId = reportDbService.insert(mEventReport);    // 将记录保存到本地数据库中
            if (addId >= 1) {                                    // 添加成功后再查总条数
                count = reportDbService.getCount();
                if (count >= MAX_LIMIT) {
                    reportDbService.deleteAll(null, false);
                } else if (count >= limitCount) {                        // 满50条上传
                    mEventReport.setData(reportDbService.getList(false));    //遍历集合
                    isCountFull = true;
                    mEventReport.setDaapContent(new Gson().toJson(new ReportModel().getAdaptReport(reportDbService.getList(false), context)));
                    SenderReport(mEventReport, context);
                    SenderDAAPReport(mEventReport, context);
                }
            }
        } catch (final Exception e) {
//            reportDbService.deleteAll(null, false);
            Log.e("operateReportFroMroImp", e.getMessage());
//            MyPost.post(new Runnable() {
//                @Override
//                public void run() {
//                    AlertDialogUtil.showAlertDialog(mContext, "", e.getMessage());
//                }
//            });
        }
    }

    /**
     * @param context 增加一个字段，如果已经增加了；就不需要重复操作
     *                未增加，就增加；添加增加标识
     */
//    private static void alterTableReport(Context context) {
//        try {
//            boolean alterReport = PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT, false);
//            if (alterReport)
//                return;
//            if (reportDbService.isFieldExist(reportDbService.getDbHelper().getWritableDatabase(), "t_onstar_report", "ipdID")) {
//                PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT, true);
//            } else {
//                reportDbService.getDbHelper().getWritableDatabase().execSQL(alter);
//                PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT, true);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

//    @Column("deviceId")
//    private String deviceId;
//    @Column("deviceType")
//    private String deviceType;
//    @Column("osType")
//    private String osType;
//    @Column("accountID")
//    private String accountID;
//    @Column("appVersion")
//    private String appVersion;

    /**
     * @param context 增加一个字段，如果已经增加了；就不需要重复操作
     *                未增加，就增加；添加增加标识
     */
//    private static void alterTableReportForMro(Context context) {
//        try {
//            boolean alterReport = PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT_FOR_MRO, false);
//            if (alterReport)
//                return;
//            if (reportDbService.isFieldExist(reportDbService.getDbHelper().getWritableDatabase(), "t_onstar_report", "appVersion")) {
//                PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT_FOR_MRO, true);
//            } else {
//                String ADD_DEVICEID = "ALTER TABLE `t_onstar_report` ADD `deviceId` VARCHAR(100)";
//                String ADD_DEVICE_TYPE = "ALTER TABLE `t_onstar_report` ADD `deviceType` VARCHAR(100)";
//                String ADD_OS_TYPE = "ALTER TABLE `t_onstar_report` ADD `osType` VARCHAR(64)";
//                String ADD_ACCOUNT_ID = "ALTER TABLE `t_onstar_report` ADD `accountID` VARCHAR(100)";
//                String ADD_APP_VERSION = "ALTER TABLE `t_onstar_report` ADD `appVersion` VARCHAR(64)";
//                SQLiteDatabase database = reportDbService.getDbHelper().getWritableDatabase();
//                database.execSQL(ADD_DEVICEID);
//                database.execSQL(ADD_DEVICE_TYPE);
//                database.execSQL(ADD_OS_TYPE);
//                database.execSQL(ADD_ACCOUNT_ID);
//                database.execSQL(ADD_APP_VERSION);
//                PreferencesUtls.getInstance(context).putBoolean(FinalConstants.SharedPreferencesConfig.ALTER_REPORT_FOR_MRO, true);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    // 统一处理发送到服务端Report
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public static void SenderReport(RequestEventReportEntity reportList, Context context) {
        OperateReportService reportService = new OperateReportService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        reportService.operateReport(requestEntity, reportList);
        Sender sender = new Sender();
        sender.send(requestEntity, commandHandler, OperateReportUtil.class, "SenderReport", RequestEventReportEntity.class, Context.class);

    }

    // 统一处理发送到服务端Report
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public static void SenderDAAPReport(RequestEventReportEntity entity, Context context) {
        OperateDAAPReportService reportService = new OperateDAAPReportService(EncryptUtil.decryptBase64(context, Constants.URL_DAAP_REPORT));
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        reportService.operateDAAPReport(requestEntity, entity);
        Sender sender = new Sender();
        LinkedHashMap<String, Object> coHashMap = new LinkedHashMap<String, Object>();
        coHashMap.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
        coHashMap.put("Accept-Encoding", "gzip");
        requestEntity.setCustomHeads(coHashMap);
        LogManager.getInstance().d("the sending report is " + requestEntity.getBody());
//        requestEntity.setBody(str);
        sender.send(requestEntity, commandHandler, OperateReportUtil.class, "SenderDAAPReport", RequestEventReportEntity.class, Context.class);

    }

    private static ResponseHandler commandHandler = new ResponseHandler() {
        @Override
        public void onSuccess(String tag, String json) {
            logger.d(json);
            // 数据上传成功后，删除本地记录的数据
            if (isCountFull) { // 本地记录满50条上传到Report
                reportDbService.deleteAll(null, false);
            }
        }

        @Override
        public void onError(String tag, HttpException e) {
            logger.d(e.getMessage());
        }
    };

    /**
     * @param pattern
     * @return String 返回类型
     * @throws
     * @Title: getDateFromPattern
     * @Description: 格式化日期
     */
    public static String getDateFromPattern(String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = new Date();
        return format.format(date);
    }

    /**
     * @return String 返回类型
     * @throws
     * @Title: getTimeStamp
     * @Description: 得到时间戳
     */
    public static String getTimeStamp() {
        return new Date().getTime() + "";
    }
}